<template>
    <div class="ware-in-out-flowing-water">
        <!-- 日期筛选 -->
        <el-card class="date-filter-card">
            <div class="date-filter">
                <el-button v-for="date in dateFilters" :key="date.key"
                    :type="selectedDateFilter === date.key ? 'primary' : 'default'" size="small"
                    @click="selectDateFilter(date.key)">
                    {{ date.label }}
                </el-button>

                <!-- 自定义时间范围选择器 -->
                <div v-if="selectedDateFilter === 'custom'" class="custom-time-picker">
                    <el-date-picker v-model="customDateRange" type="daterange" range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                        size="small" @change="handleCustomDateChange" />
                    <el-button type="primary" size="small" @click="searchWithCustomDate">
                        查询
                    </el-button>
                </div>
            </div>
        </el-card>

        <!-- 搜索过滤区域 -->
        <el-card class="search-filter-card">
            <el-form :inline="true" :model="queryForm" class="search-form" label-width="90px">
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="出入库单号：">
                            <el-input v-model="queryForm.warehouse_Code" placeholder="请输入出入库单号" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="出入库类型：">
                            <el-select v-model="queryForm.warehouseType" placeholder="请选择" clearable>
                                <el-option label="入库" :value="1" />
                                <el-option label="出库" :value="2" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="仓库名称：">
                            <el-select v-model="queryForm.warehouse_ID" placeholder="请选择" clearable>
                                <el-option v-for="item in warehouseList" :label="item.warehouse_Name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="经办人：">
                            <el-input v-model="queryForm.reviewer" placeholder="请输入" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="货品：">
                            <el-input v-model="queryForm.product_NameOrNumber" placeholder="请输入货品名称/编号" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="货品类型：">
                            <el-tree-select v-model="queryForm.category_ID" :data="categoryTreeList" placeholder="请选择"
                                clearable check-strictly :props="{
                                    children: 'children',
                                    label: 'category_Name',
                                    value: 'id',
                                }" style="width: 200px" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="单位：">
                            <el-select v-model="queryForm.unit_ID" placeholder="请选择" clearable>
                                <el-option v-for="item in UnitList" :label="item.unit_Name" :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="出入库时间：">
                            <el-date-picker v-model="dateRange" type="daterange" range-separator="至"
                                start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD" clearable style="width: 200px"
                                @change="handleDateRangeChange" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8"></el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="所属部门:">
                            <el-select v-model="queryForm.department_ID" placeholder="请选择" clearable>
                                <el-option v-for="item in DepartmentList" :label="item.department_Name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="制单时间：">
                            <el-date-picker v-model="queryForm.createTime" type="date" placeholder="请选择日期"
                                format="YYYY-MM-DD" value-format="YYYY-MM-DD" clearable style="width: 200px" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8"></el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item>
                            <el-button type="default" @click="resetForm">重置</el-button>
                            <el-button type="primary" @click="search">查询</el-button>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8"></el-col>
                    <el-col :span="8"></el-col>
                </el-row>
            </el-form>
        </el-card>

        <!-- 统计卡片 -->
        <el-row :gutter="24" class="stats-row">
            <el-col :span="12">
                <el-card>
                    <div class="stat-group stat-group-left">
                        <div class="stat-item">
                            <div class="stat-value blue">{{ statistics.totalOrders }}</div>
                            <div class="stat-title">出入库单数量</div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-value blue">{{ statistics.inOrders }}</div>
                            <div class="stat-title">入库单数量</div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-value blue">{{ statistics.outOrders }}</div>
                            <div class="stat-title">出库单数量</div>
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card>
                    <div class="stat-group stat-group-right">
                        <div class="stat-item">
                            <div class="stat-value green">{{ statistics.inQuantity }}</div>
                            <div class="stat-title">入库数量</div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-value green">¥{{ statistics.inAmount }}</div>
                            <div class="stat-title">入库金额</div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-value orange">{{ statistics.outQuantity }}</div>
                            <div class="stat-title">出库数量</div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-value orange">¥{{ statistics.outAmount }}</div>
                            <div class="stat-title">出库金额</div>
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>

        <!-- 表格操作按钮 -->
        <el-card class="table-actions-card">
            <el-button type="primary" @click="exportData">
                导出{{
                    selectedRows.length > 0 ? `(${selectedRows.length}条)` : "(全部)"
                }}
            </el-button>
            <el-button type="default" @click="refreshData">刷新</el-button>
        </el-card>

        <!-- 数据表格 -->
        <el-card class="table-card">
            <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" fixed="left" />
                <el-table-column type="index" label="序号" width="60" fixed="left" />
                <el-table-column prop="warehouse_Code" label="出入库单号" width="100" fixed="left" />
                <el-table-column prop="reviewTime" label="出入库时间" width="120" fixed="left">
                    <template #default="scope">
                        {{
                            scope.row.reviewTime
                                ? moment(scope.row.reviewTime).format("YYYY-MM-DD")
                                : "--"
                        }}
                    </template>
                </el-table-column>
                <el-table-column prop="warehousing_Type" label="出入库类型" width="100" fixed="left" />
                <el-table-column prop="product_Number" label="产品编号" width="120" />
                <el-table-column prop="product_Name" label="产品名称" width="120" />
                <el-table-column prop="specifications" label="规格型号" width="100" />
                <el-table-column prop="unit_Name" label="单位" width="80" />
                <el-table-column prop="category_Name" label="类别" width="100" />
                <el-table-column prop="inPrice" label="入库单价" width="100" />
                <el-table-column prop="outPrice" label="出库单价" width="100" />
                <el-table-column prop="inCount" label="入库数量" width="100" />
                <el-table-column prop="outCount" label="出库数量" width="100" />
                <el-table-column prop="inTotalPrice" label="入库金额" width="100" />
                <el-table-column prop="outTotalPrice" label="出库金额" width="100" />
                <el-table-column prop="warehouse_Name" label="仓库" width="120" />
                <el-table-column prop="storage_Name" label="库位" width="120" />
                <el-table-column prop="department_Name" label="部门" width="120" />
                <el-table-column prop="reviewer" label="经办人" width="100" />
                <el-table-column prop="reviewTime" label="审核时间" width="150">
                    <template v-slot="scope">
                        {{
                            scope.row.reviewTime
                                ? moment(scope.row.reviewTime).format("YYYY-MM-DD HH:mm:ss")
                                : "--"
                        }}
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 分页 -->
        <table>
            <tr>
                <td>
                    <el-pagination v-model:current-page="pageQuery.pageindex" v-model:page-size="pageQuery.pagesize"
                        :page-sizes="[15, 20, 30]" :size="size" background="true" layout="slot, sizes"
                        :total="pageQuery.totalCount">
                        共{{ pageQuery.totalCount }}条 每页显示{{ pageQuery.pagesize }}条
                        当前第{{ pageQuery.pageindex }}页/共{{ pageQuery.totalPage }}页
                    </el-pagination>
                </td>
                <td>
                    <el-pagination v-model:current-page="pageQuery.pageindex" v-model:page-size="pageQuery.pagesize"
                        :page-sizes="[15, 20, 30]" :size="size" background="true" layout="slot, prev, pager, next"
                        :total="pageQuery.totalCount" prev-text="上一页" next-text="下一页">
                        <el-button :disabled="pageQuery.pageindex == 1" @click="pageQuery.pageindex = 1">首页</el-button>
                    </el-pagination>
                </td>
                <td>
                    <el-pagination v-model:current-page="pageQuery.pageindex" v-model:page-size="pageQuery.pagesize"
                        :page-sizes="[15, 20, 30]" :size="size" background="true" layout="slot,jumper"
                        :total="pageQuery.totalCount">
                        <el-button :disabled="pageQuery.pageindex == pageQuery.totalPage"
                            @click="pageQuery.pageindex = pageQuery.totalPage">尾页</el-button>
                    </el-pagination>
                </td>
            </tr>
        </table>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from "vue";
import { ElMessage } from "element-plus";
import type { ComponentSize } from "element-plus";
const size = ref<ComponentSize>("default");
import { statementRed } from "@/http/axiosHelper";
import moment from "moment";

// 日期筛选选项
const dateFilters = [
    { key: "today", label: "今日" },
    { key: "yesterday", label: "昨日" },
    { key: "thisWeek", label: "本周" },
    { key: "lastWeek", label: "上周" },
    { key: "thisMonth", label: "本月" },
    { key: "lastMonth", label: "上月" },
    { key: "custom", label: "自定义时间" },
];

const selectedDateFilter = ref("today");

// 自定义时间范围
const customDateRange = ref<[string, string] | null>(null);

// 日期范围选择器
const dateRange = ref<string[]>([]);

// 查询表单
const queryForm = reactive({
    warehouseType: "",
    warehouse_Code: "",
    warehousing_Type: "",
    warehouse_ID: "",
    reviewer: "",
    product_NameOrNumber: "",
    category_ID: "",
    unit_ID: "",
    startTime: "",
    endTime: "",
    department_ID: "",
    createTime: "",
});

const pageQuery: any = reactive({
    pageindex: 1,
    pagesize: 15,
    totalCount: "",
    totalPage: "",
});

const tableData = ref([]);

onMounted(() => {
    search();
    getWarehouseList();
    getUnitList();
    getDepartmentList();
    getCategoryTreeList();
});

const search = () => {
    console.log("开始搜索，查询参数:", {
        startTime: queryForm.startTime,
        endTime: queryForm.endTime,
        warehouseType: queryForm.warehouseType,
        warehouse_Code: queryForm.warehouse_Code,
        pageindex: pageQuery.pageindex,
        pagesize: pageQuery.pagesize,
    });

    statementRed({
        url: "api/WorkOrder/GetWareInOrOut_FlowingWater",
        method: "get",
        params: {
            warehouseType: queryForm.warehouseType,
            warehouse_Code: queryForm.warehouse_Code,
            warehousing_Type: queryForm.warehousing_Type,
            warehouse_ID: queryForm.warehouse_ID,
            createTime: queryForm.createTime,
            department_ID: queryForm.department_ID,
            startTime: queryForm.startTime,
            endTime: queryForm.endTime,
            product_NameOrNumber: queryForm.product_NameOrNumber,
            category_ID: queryForm.category_ID,
            unit_ID: queryForm.unit_ID,
            reviewer: queryForm.reviewer,
            pageindex: pageQuery.pageindex,
            pagesize: pageQuery.pagesize,
        },
    })
        .then((res: any) => {
            console.log("搜索返回数据:", res.data);
            tableData.value = res.data.data || [];
            pageQuery.totalCount = res.data.totalCount || 0;
            pageQuery.totalPage = res.data.totalPage || 0;

            // 计算统计数据
            calculateStatistics();
        })
        .catch((error: any) => {
            console.error("搜索失败:", error);
            tableData.value = [];
            pageQuery.totalCount = 0;
            pageQuery.totalPage = 0;
            // 重置统计数据
            calculateStatistics();
        });
};

watch(pageQuery, () => {
    search();
});

// 仓库列表
const warehouseList: any = ref([]);
// 获取仓库列表
const getWarehouseList = () => {
    statementRed({
        url: "api/Warehouse_InOrOut/GetWarehouseModel",
        method: "get",
    }).then((res) => {
        warehouseList.value = res.data.data;
    });
};

// 单位列表
const UnitList: any = ref([]);
// 获取单位列表
const getUnitList = () => {
    statementRed({
        url: "api/WorkOrder/GetUnitDropdown",
        method: "get",
    }).then((res) => {
        UnitList.value = res.data.data;
    });
};

// 部门列表
const DepartmentList: any = ref([]);
// 获取部门列表
const getDepartmentList = () => {
    statementRed({
        url: "api/WorkOrder/GetDepartmentDropdown",
        method: "get",
    }).then((res) => {
        DepartmentList.value = res.data.data;
    });
};

// 产品类型树形列表
const categoryTreeList: any = ref([]);
// 获取产品类型树形结构
const getCategoryTreeList = () => {
    statementRed({
        url: "api/WorkOrder/GetProductCategoryTree",
        method: "get",
    }).then((res) => {
        categoryTreeList.value = res.data.data;
    });
};

// 统计数据
const statistics = reactive({
    totalOrders: 0,
    inOrders: 0,
    outOrders: 0,
    inQuantity: 0,
    inAmount: "0.00",
    outQuantity: 0,
    outAmount: "0.00",
});

// 计算统计数据的方法
const calculateStatistics = () => {
    // 重置统计数据
    statistics.totalOrders = tableData.value.length;
    statistics.inOrders = 0;
    statistics.outOrders = 0;
    statistics.inQuantity = 0;
    let inAmountTotal = 0;
    statistics.outQuantity = 0;
    let outAmountTotal = 0;

    console.log("开始计算统计数据，当前数据条数:", tableData.value.length);

    // 遍历表格数据计算统计信息
    tableData.value.forEach((item: any, index: number) => {
        console.log(`处理第${index + 1}条数据:`, {
            warehousing_Type: item.warehousing_Type,
            inCount: item.inCount,
            outCount: item.outCount,
            inTotalPrice: item.inTotalPrice,
            outTotalPrice: item.outTotalPrice,
            inPrice: item.inPrice,
            outPrice: item.outPrice,
        });

        // 根据入库相关字段判断是否有入库数据
        if (item.inCount && Number(item.inCount) > 0) {
            statistics.inOrders++;
            // 累加入库数量
            statistics.inQuantity += Number(item.inCount);
            // 累加入库金额 - 优先使用inTotalPrice，如果没有则计算
            let inAmount = 0;
            if (item.inTotalPrice && Number(item.inTotalPrice) > 0) {
                inAmount = Number(item.inTotalPrice);
            } else if (item.inPrice && item.inCount) {
                // 如果没有总价，用单价乘以数量
                inAmount = Number(item.inPrice) * Number(item.inCount);
            }
            inAmountTotal += inAmount;
            console.log(
                `入库数据: 数量=${item.inCount}, 单价=${item.inPrice}, 总价=${item.inTotalPrice}, 计算金额=${inAmount}`
            );
        }

        // 根据出库相关字段判断是否有出库数据
        if (item.outCount && Number(item.outCount) > 0) {
            statistics.outOrders++;
            // 累加出库数量
            statistics.outQuantity += Number(item.outCount);
            // 累加出库金额 - 优先使用outTotalPrice，如果没有则计算
            let outAmount = 0;
            if (item.outTotalPrice && Number(item.outTotalPrice) > 0) {
                outAmount = Number(item.outTotalPrice);
            } else if (item.outPrice && item.outCount) {
                // 如果没有总价，用单价乘以数量
                outAmount = Number(item.outPrice) * Number(item.outCount);
            }
            outAmountTotal += outAmount;
            console.log(
                `出库数据: 数量=${item.outCount}, 单价=${item.outPrice}, 总价=${item.outTotalPrice}, 计算金额=${outAmount}`
            );
        }
    });

    // 格式化金额显示
    statistics.inAmount = inAmountTotal.toFixed(2);
    statistics.outAmount = outAmountTotal.toFixed(2);

    console.log("统计结果:", {
        totalOrders: statistics.totalOrders,
        inOrders: statistics.inOrders,
        outOrders: statistics.outOrders,
        inQuantity: statistics.inQuantity,
        inAmount: statistics.inAmount,
        outQuantity: statistics.outQuantity,
        outAmount: statistics.outAmount,
        inAmountTotal: inAmountTotal,
        outAmountTotal: outAmountTotal,
    });
};

// 选中的行
const selectedRows = ref<any[]>([]);

// 处理表格选择变化
const handleSelectionChange = (selection: any[]) => {
    selectedRows.value = selection;
    console.log("选中的行:", selection.length, "条");
};

// 方法
const selectDateFilter = (key: string) => {
    selectedDateFilter.value = key;

    // 根据选择的日期筛选设置查询参数
    const today = moment();

    switch (key) {
        case "today":
            // 今日
            queryForm.startTime = today.format("YYYY-MM-DD");
            queryForm.endTime = today.format("YYYY-MM-DD");
            break;
        case "yesterday":
            // 昨日
            queryForm.startTime = today.subtract(1, "days").format("YYYY-MM-DD");
            queryForm.endTime = queryForm.startTime;
            break;
        case "thisWeek":
            // 本周
            queryForm.startTime = today.startOf("week").format("YYYY-MM-DD");
            queryForm.endTime = today.endOf("week").format("YYYY-MM-DD");
            break;
        case "lastWeek":
            // 上周
            queryForm.startTime = today
                .subtract(1, "week")
                .startOf("week")
                .format("YYYY-MM-DD");
            queryForm.endTime = today
                .subtract(1, "week")
                .endOf("week")
                .format("YYYY-MM-DD");
            break;
        case "thisMonth":
            // 本月
            queryForm.startTime = today.startOf("month").format("YYYY-MM-DD");
            queryForm.endTime = today.endOf("month").format("YYYY-MM-DD");
            break;
        case "lastMonth":
            // 上月
            queryForm.startTime = today
                .subtract(1, "month")
                .startOf("month")
                .format("YYYY-MM-DD");
            queryForm.endTime = today
                .subtract(1, "month")
                .endOf("month")
                .format("YYYY-MM-DD");
            break;
        case "custom":
            // 自定义时间 - 清空日期范围，让用户手动选择
            queryForm.startTime = "";
            queryForm.endTime = "";
            dateRange.value = [];
            break;
    }

    // 如果不是自定义时间，设置日期范围选择器的值
    if (key !== "custom") {
        dateRange.value = [queryForm.startTime, queryForm.endTime];
    }

    console.log(
        `选择日期筛选: ${key}, 日期范围: ${queryForm.startTime} 到 ${queryForm.endTime}`
    );

    // 如果不是自定义时间，重置页码并执行搜索
    if (key !== "custom") {
        pageQuery.pageindex = 1;
        search();
    }
};

// 处理日期范围变化
const handleDateRangeChange = (dates: any) => {
    if (dates && dates.length === 2) {
        queryForm.startTime = dates[0];
        queryForm.endTime = dates[1];
        // 当用户手动选择日期范围时，设置为自定义模式
        selectedDateFilter.value = "custom";
    } else {
        queryForm.startTime = "";
        queryForm.endTime = "";
    }
    // 重置页码并执行搜索
    pageQuery.pageindex = 1;
    search();
};

// 处理自定义时间范围变化
const handleCustomDateChange = (dates: [string, string] | null) => {
    if (dates && dates.length === 2) {
        queryForm.startTime = dates[0];
        queryForm.endTime = dates[1];
        console.log(`自定义时间范围: ${dates[0]} 到 ${dates[1]}`);
    }
};

// 使用自定义时间进行查询
const searchWithCustomDate = () => {
    if (customDateRange.value && customDateRange.value.length === 2) {
        queryForm.startTime = customDateRange.value[0];
        queryForm.endTime = customDateRange.value[1];
        pageQuery.pageindex = 1;
        search();
        ElMessage.success("自定义时间查询成功");
    } else {
        ElMessage.warning("请选择时间范围");
    }
};

// 重置按钮
const resetForm = () => {
    queryForm.warehouseType = "";
    queryForm.warehouse_Code = "";
    queryForm.warehousing_Type = "";
    queryForm.warehouse_ID = "";
    queryForm.reviewer = "";
    queryForm.product_NameOrNumber = "";
    queryForm.category_ID = "";
    queryForm.unit_ID = "";
    queryForm.startTime = "";
    queryForm.endTime = "";
    queryForm.department_ID = "";
    queryForm.createTime = "";
    dateRange.value = [];
    // 清空选中的行
    selectedRows.value = [];
    // 重置日期筛选为今日
    selectedDateFilter.value = "today";
    // 设置今日的日期范围
    const today = moment();
    queryForm.startTime = today.format("YYYY-MM-DD");
    queryForm.endTime = today.format("YYYY-MM-DD");
    dateRange.value = [queryForm.startTime, queryForm.endTime];
    // 重置页码并搜索
    pageQuery.pageindex = 1;
    search();
};

// 搜索数据
const searchData = () => {
    // 调用实际的搜索方法
    search();
};

//导出
async function exportData() {
    try {
        // 准备导出参数
        const exportParams: any = {
            warehouseType: queryForm.warehouseType,
            warehouse_Code: queryForm.warehouse_Code,
            warehousing_Type: queryForm.warehousing_Type,
            warehouse_ID: queryForm.warehouse_ID,
            reviewer: queryForm.reviewer,
            product_NameOrNumber: queryForm.product_NameOrNumber,
            category_ID: queryForm.category_ID,
            unit_ID: queryForm.unit_ID,
            startTime: queryForm.startTime,
            endTime: queryForm.endTime,
            department_ID: queryForm.department_ID,
            pageindex: pageQuery.pageindex,
            pagesize: pageQuery.pagesize,
        };

        // 如果有选中的行，添加选中行的ID列表
        if (selectedRows.value.length > 0) {
            const selectedIds = selectedRows.value.map(
                (row: any) => row.id || row.warehouse_Code
            );
            exportParams.selectedIds = selectedIds;
            console.log("导出选中的数据:", selectedRows.value.length, "条");
        } else {
            console.log("导出全部数据");
        }

        // 1. 调用后端导出接口（GET 请求，参数通过 params 传递）
        const response = await statementRed({
            url: "api/WorkOrder/loadWareInOrOut_FlowingWater", // 后端接口地址
            method: "GET",
            params: exportParams, // 对应后端 [FromQuery] 的 command 参数
            responseType: "blob", // 关键：指定响应类型为二进制流（Excel 文件）
        });

        // 2. 从响应头获取文件名（后端通过 File 方法设置的 fileName）
        const fileName = getFileNameFromHeaders(response.headers);

        // 3. 生成下载链接并触发下载
        const blob = new Blob([response.data], {
            type:
                response.headers["content-type"] ||
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = fileName; // 文件名从响应头获取或自定义
        document.body.appendChild(a);
        a.click();

        // 4. 清理资源
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
    } catch (error: any) {
        // 处理错误（如后端返回 401/400 等）
        console.error("导出失败：", error.response?.data || error.message);
        alert("导出失败，请检查参数或重新登录");
    }
}

// 辅助函数：从响应头提取文件名（后端通过 File 方法设置）
function getFileNameFromHeaders(headers: any) {
    const contentDisposition =
        headers["content-disposition"] || headers["Content-Disposition"];
    if (!contentDisposition) return "出入库流水信息列表.xlsx"; // 默认文件名

    // 解码文件名（处理中文编码问题）
    const match = contentDisposition.match(/filename\*?=([^;]+)/);
    if (match) {
        return decodeURIComponent(match[1].replace(/["']/g, ""));
    }
    return "出入库流水信息列表.xlsx";
}

// 刷新数据
const refreshData = () => {
    search();
    ElMessage.success("数据刷新成功");
};
</script>

<style scoped>
.ware-in-out-flowing-water {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

.date-filter-card {
    margin-bottom: 20px;
    background: white;
}

.date-filter {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    align-items: center;
}

.custom-time-picker {
    display: flex;
    gap: 10px;
    align-items: center;
    margin-left: 10px;
}

.date-filter .el-button {
    border-radius: 20px;
    padding: 8px 16px;
}

.search-filter-card {
    margin-bottom: 20px;
    background: white;
    padding: 24px 16px 16px 16px;
    overflow-x: auto;
    max-width: 100vw;
}

.search-form {
    padding: 0;
    min-width: 900px;
}

.more-btn {
    margin-left: 5px;
    color: #409eff;
}

.stats-card {
    margin-bottom: 20px;
    background: white;
}

.stat-item {
    text-align: center;
    padding: 20px;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: transform 0.2s ease;
}

.stat-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-title {
    font-size: 14px;
    color: #666;
    margin-bottom: 10px;
    font-weight: 500;
}

.stat-value {
    font-size: 28px;
    font-weight: bold;
    margin-top: 5px;
}

.stat-value.blue {
    color: #409eff;
}

.stat-value.green {
    color: #67c23a;
}

.stat-value.orange {
    color: #e6a23c;
}

.table-actions-card {
    margin-bottom: 20px;
    background: white;
    padding: 15px 20px;
}

.table-actions-card .el-button {
    margin-right: 10px;
    border-radius: 6px;
}

.table-card {
    margin-bottom: 20px;
    background: white;
}

.table-card .el-table {
    border-radius: 8px;
    overflow: hidden;
}

.pagination-card {
    text-align: right;
    background: white;
    padding: 15px 20px;
}

/* 移除重复的样式 */

:deep(.el-input) {
    width: 200px !important;
}

:deep(.el-select) {
    width: 200px !important;
}

:deep(.el-tree-select) {
    width: 200px !important;
}

:deep(.el-date-picker) {
    width: 200px !important;
}

:deep(.el-date-editor--daterange) {
    width: 200px !important;
}

:deep(.el-form-item__content) {
    flex-wrap: nowrap;
}

:deep(.el-form-item) {
    display: flex !important;
    align-items: center;
    min-width: 260px;
    margin-bottom: 18px;
    margin-right: 28px;
}

:deep(.el-form-item__label) {
    min-width: 90px;
    width: 90px;
    margin-right: 12px !important;
    text-align: right;
    flex-shrink: 0;
    font-size: 14px;
    color: #333;
    background: transparent;
    display: inline-block;
    white-space: nowrap;
}

:deep(.el-card) {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-table th) {
    background-color: #f8f9fa;
    color: #333;
    font-weight: 600;
}

:deep(.el-table td) {
    padding: 12px 0;
}

:deep(.el-button--primary) {
    background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
    border: none;
}

:deep(.el-button--primary:hover) {
    background: linear-gradient(135deg, #337ecc 0%, #2d6aad 100%);
}

.stats-row {
    margin-bottom: 0;
}

.stat-group {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    width: 100%;
    overflow-x: auto;
    gap: 32px;
    padding-bottom: 4px;
}

.stat-group-left .stat-item {
    flex: 0 0 auto;
    min-width: 120px;
}

.stat-group-right .stat-item {
    flex: 0 0 auto;
    min-width: 120px;
}

.stat-item {
    text-align: center;
    padding: 16px 0;
    background: none;
    box-shadow: none;
    border-radius: 0;
}

.stat-value {
    font-size: 32px;
    font-weight: bold;
    margin-bottom: 8px;
}

.stat-title {
    font-size: 15px;
    color: #222;
}

.stat-value.blue {
    color: #409eff;
}

.stat-value.green {
    color: #67c23a;
}

.stat-value.orange {
    color: #e6a23c;
}

:deep(.el-card) {
    box-shadow: none !important;
}
</style>